package ge.gen.eBdgt.action.graph;

import ge.gen.eBdgt.action.graph.CreateChart.MyGenerator;
import ge.gen.eBdgt.vo.TeamWrkLoadVO;

import java.awt.Color;
import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.TreeSet;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.labels.CategoryToolTipGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.urls.CategoryURLGenerator;
import org.jfree.data.category.CategoryDataset;

import com.opensymphony.xwork2.ActionContext;

public class IcnTeamWrkLdGraph {
	private JFreeChart chart;
	public ActionContext ac;
	public String imagesPath;
	private List<TeamWrkLoadVO> teamWrkLoad;
	private HashMap regengrMap;
	String currentPath;

	public IcnTeamWrkLdGraph(List<TeamWrkLoadVO> teamWrkLoad, String currentPath) {
		this.teamWrkLoad = teamWrkLoad;
		this.currentPath = currentPath;
	}

	private IcnDataset createDataset(List list) {
		String prev = "";
		int j, k;
		Comparable[] rowKeys = new Comparable[list.size()];
		Comparable[] columnKeys = new Comparable[list.size()];
		IcnDataset dataset = new IcnDataset();
		double[][] data = new double[list.size()][list.size()];
		j = -1;
		k = 0;
		for (int i = 0; i < list.size(); i++) {
			String vo = (String) list.get(i);
			String s[] = vo.split("\\s");

			if (prev.equals(s[0]) == false) {
				j++;
				k = 0;
				rowKeys[j] = s[0];
				columnKeys[j] = "" + i;
			}
			dataset.addValue(1, s[1], s[0]);
			dataset.insertIcn(s[1]);
			data[j][k] = 1;
			prev = s[0];
			k++;
		}

		// return DatasetUtilities.createCategoryDataset(rowKeys, columnKeys,
		// data);
		return dataset;
	}

	public boolean isBlank(String s) {
		return s == null || s.length() <= 0;
	}

	public HashMap getSortedMap(HashMap hmap) {
		if (hmap == null || hmap.size() <= 0)
			return hmap;
		HashMap map = new LinkedHashMap();
		List mapKeys = new ArrayList(hmap.keySet());
		List mapValues = new ArrayList(hmap.values());
		hmap.clear();
		TreeSet sortedSet = new TreeSet(mapValues);
		Object[] sortedArray = sortedSet.toArray();
		int size = sortedArray.length;
		for (int i = 0; i < size; i++) {
			map.put(mapKeys.get(mapValues.indexOf(sortedArray[i])),
					sortedArray[i]);
		}
		return map;
	}

	public JFreeChart createChart(final IcnDataset dataset, HashMap regengrMap) {

		final JFreeChart chart = ChartFactory.createStackedBarChart(
				"Team Work Load", // chart
				// title
				"", // domain axis label
				"No of Icns", // range axis label
				dataset, // data
				PlotOrientation.VERTICAL, // the plot orientation
				false, // legend
				true, // tooltips
				false // urls
				);
		chart.setBackgroundPaint(new Color(249, 231, 236));
		CategoryPlot plot = chart.getCategoryPlot();
		plot.getRenderer().setSeriesPaint(0, new Color(128, 0, 0));
		plot.getRenderer().setSeriesPaint(1, new Color(0, 0, 255));

		CategoryItemRenderer renderer = plot.getRenderer();
		MyGenerator generator = new MyGenerator("\\GenReport", "series1",
				"categry1");
		renderer.setBaseItemURLGenerator(generator);
		renderer.setBaseToolTipGenerator(generator);
		return chart;
	}

	public class MyGenerator implements CategoryURLGenerator,
			CategoryToolTipGenerator {
		private String prefix = "index.html";
		private String seriesParameterName = "series";
		private String categoryParameterName = "category";
		private String rangeParameterName = "range";
		private String rangeKey = null;

		private CategoryDataset theDataset = null;

		public MyGenerator(String prefix, CategoryDataset ds) {
			super();
			this.prefix = prefix;
			this.theDataset = ds;
		}

		public MyGenerator(String prefix) {
			this.prefix = prefix;
		}

		public MyGenerator(String prefix, String rangeKey,
				CreateChart createChart) {
			this.prefix = prefix;
			this.rangeKey = rangeKey;
		}

		public MyGenerator(String prefix, String seriesParameterName,
				String categoryParameterName) {
			this.prefix = prefix;
			this.seriesParameterName = seriesParameterName;
			this.categoryParameterName = categoryParameterName;
		}

		public MyGenerator(String prefix, String seriesParameterName,
				String categoryParameterName, String rangeParameterName,
				String rangeKey) {
			this.prefix = prefix;
			this.seriesParameterName = seriesParameterName;
			this.categoryParameterName = categoryParameterName;
			this.rangeParameterName = rangeParameterName;
			this.rangeKey = rangeKey;
		}

		public String myGenerateURL(Comparable seriesKey,
				Comparable categoryKey, Comparable rangeKey) {
			if (categoryKey.toString().equals("<<REST>>")
					|| seriesKey.toString().equals("<<REST>>")
					|| (rangeKey != null && rangeKey.toString().equals(
							"<<REST>>"))) {
				return "";
			}

			String url = this.prefix;
			boolean firstParameter = url.indexOf("?") == -1;

			if (categoryKey.toString().equals("rest_value")) {
				return "";
			}
			if (seriesKey.toString().equals("rest_serie")) {
				return "";
			}

			url += firstParameter ? "?" : "&";
			try {
				url += this.seriesParameterName + "="
						+ URLEncoder.encode(seriesKey.toString(), "UTF-8");
				url += "&" + this.categoryParameterName + "="
						+ URLEncoder.encode(categoryKey.toString(), "UTF-8");
				if (rangeKey != null) {
					url += "&" + this.rangeParameterName + "="
							+ URLEncoder.encode(rangeKey.toString(), "UTF-8");
				}
			} catch (java.io.UnsupportedEncodingException uee) {
				uee.printStackTrace();
			}

			return url;
		}

		public String myGenerateToolTip(Comparable seriesKey,
				Comparable categoryKey, Comparable rangeKey, Number value) {
			String text = "";
			if (this.rangeKey != null && !this.rangeKey.equals("<<NULL>>")) {
				text += this.rangeKey + ", ";
			}

			if (seriesKey != null && !seriesKey.toString().equals("<<NULL>>")) {
				text += seriesKey.toString() + ", ";
			}

			text += "this.createChart.xAxis =" + categoryKey.toString() + ", ";

			text += "value: " + value;
			return text;
		}

		/** Category **/

		public String generateURL(CategoryDataset dataset, int series,
				int category) {
			Comparable seriesKey = dataset.getRowKey(series);
			Comparable categoryKey = dataset.getColumnKey(category);

			return myGenerateURL(seriesKey, categoryKey, this.rangeKey);
		}

		public String generateToolTip(CategoryDataset dataset, int series,
				int category) {
			Comparable seriesKey = dataset.getRowKey(series);
			Comparable categoryKey = dataset.getColumnKey(category);

			return myGenerateToolTip(seriesKey, categoryKey, this.rangeKey,
					dataset.getValue(seriesKey, categoryKey));
		}

	}

	public JFreeChart getChart() {
		return chart;
	}

	private ArrayList createData() {
		int num = 0;
		String prevEng = "";
		ArrayList list = new ArrayList();
		regengrMap = new HashMap();
		//teamWrkLoad = icnService.getTeamWrkLoad();
		Iterator<TeamWrkLoadVO> iter = teamWrkLoad.iterator();
		for (int i = 0; i < teamWrkLoad.size(); i++) {
			TeamWrkLoadVO vo = teamWrkLoad.get(i);
			if (vo != null && isBlank(vo.getReqEng()) == false) {
				String eng = vo.getReqEng().replaceAll(" ", "_");
				list.add(eng + " " + vo.getIcn());
				if (prevEng.equals(eng) == false) {
					num++;
				}
				System.out.println(eng + " " + vo.getIcn() + ", G" + num);
				regengrMap.put(eng + " " + vo.getIcn(), "G" + num);
				prevEng = eng;
			}
		}
		return list;
	}

	public void generate() throws Exception {
		teamWrkLoad = createData();
		final IcnDataset dataset = createDataset(teamWrkLoad);
		JFreeChart chart = createChart(dataset, regengrMap);
		chart.setBackgroundPaint(new Color(249, 231, 236));
		File uploadDir = new File(currentPath + "//");
		File file1 = new File(uploadDir, "graph_reqengr.png");
		final ChartRenderingInfo info = new ChartRenderingInfo(
				new StandardEntityCollection());
		ChartUtilities.saveChartAsPNG(file1, chart, 2000, 2000, info);

	}
}
